<?php  
/**
 * 小程序入口
 * [WeEngine System] Copyright (c) 2013 WE7.CC
 */
defined('IN_IA') or exit('Access Denied');
 
require IA_ROOT . '/addons/kbwdl_shequzufang/vender/element.class.php';
require IA_ROOT .'/addons/kbwdl_shequzufang/vendor/autoload.php';

 
class kbwdl_shequzufangModuleWxapp extends WeModuleWxapp {

    public $_uniacid = 0;
    public $other =  null;
    public $_forms =  null;
    
    public function __construct() {
        global $_GPC, $_W;
        $uniacid = $_W['uniacid'];    
        $this->_uniacid = $_W['uniacid'];
         /*获取配置参数*/
        //$this->_load_config();
        

    }
    public function checkClientSign() {
		global $_GPC;
		if (!empty($_GET) && !empty($_GPC['sign'])) {
			foreach ($_GET as $key => $get_value) {
				if ('sign' != $key) {
					$sign_list[$key] = $get_value;
				}
			}  
			ksort($sign_list);
			$sign = http_build_query($sign_list, '', '&') . '&kbwdl_shequzufang001' ;

			return md5($sign) == $_GPC['sign'];
		} else {
			return false;
		}
	}

    public function _load_config(){
        global $_GPC, $_W;
        $adapter =  include  IA_ROOT. "/addons/kbwdl_shequzufang/vender/adapter.php";
       
        $this->_forms = $adapter['sechouse'];
        $this->other = $adapter['newhouse'];
            
        $sql = 'SELECT `settings` FROM ' . tablename('uni_account_modules') . ' WHERE `uniacid` = :uniacid AND `module` = :module';
        $settings = pdo_fetchcolumn($sql, array(':uniacid' => $_W['uniacid'], ':module' => 'kbwdl_shequzufang'));
        
         $settings =   iunserializer($settings);
         //参数覆盖 
         if(isset($settings['charges_category']) && $settings['charges_category']){
            $ccstr = trim($settings['charges_category']);
            $cc = explode('|', '请选择|'. $ccstr);
            unset($cc[0]);
            $this->_forms['charges_step'] = $cc;
        }
        
        if(isset($settings['newhouse_category']) && $settings['newhouse_category']){
            $ccstr = trim($settings['newhouse_category']);
            $cc = explode('|', '请选择|'. $ccstr);
            unset($cc[0]);
            $this->other['saletype'] = $cc;
        }
        
    }
   /**
    * 
    * @global type $_GPC
    * @global type $_W
    * @param type $notice_type
    * @param type $first
    * @param type $keyword1
    * @param type $keyword2
    * @param type $remark
    * @param type $touser
    * @return boolean
    */         
    public function _send_notice_account($notice_type='', $first='', $keyword1='关键词1', $keyword2='关键词2', $remark='备注', $touser='')
    {
         global $_GPC, $_W;
         $uniacid =  $this->_uniacid;  
         $gzhinfo = pdo_fetch("select * from ".tablename("kbwdl_config"). " where placeid=41 and uniacid='$uniacid' and module='kbwdl_shequzufang'");
         load()->func('logging');
         //logging_run($gzhinfo);
         if(!empty($gzhinfo['conf_value'])){
             $gzh = iunserializer($gzhinfo['conf_value']);
         }else{
             return false;
         }
         /*判断类型是否开启*/
         if(empty($notice_type) ||  $gzh[$notice_type]!=1){
             return false;
         }        
         $helper = new \Wdl\helper\wdlHelper();
      
         if(empty($gzh['appid']) || empty($gzh['appsecret'])){
             return false;
         }
         $ACCESS_TOKEN  = $helper->getAccessToken($gzh['appid'], $gzh['appsecret']);
         if(!$ACCESS_TOKEN){
             return false; /*token 失败*/
         }
         
         // logging_run($ACCESS_TOKEN);
         if(!empty($touser)){
             $content['touser'] = trim($touser);
         }else{
             $content['touser'] = $gzh['adminopenid'];
         }
         
         $content['template_id'] = $gzh['template_id'];
         $content['url'] =  '';
         $content['topcolor'] =  '#FF0000';
         $content['data']['first']['value'] = $first;
         $content['data']['keyword1']['value'] = $keyword1;
         $content['data']['keyword2']['value'] =$keyword2;
         $content['data']['remark']['value'] = $remark;
         $tmpmsg = '{
                    "touser":"'.$content['touser'].'",
                    "template_id":"'.$content['template_id'] .'",                  
                    "topcolor":"#FF0000",
                    "data":{
                            "first": {
                                "value":"'.$content['data']['first']['value'].'",
                                "color":"#bf0000"
                            },
                            "keyword1":{
                                "value":"'.$content['data']['keyword1']['value'].'",
                                "color":"#173177"
                            },
                            "keyword2":{
                                "value":"'.$content['data']['keyword2']['value'].'",
                                "color":"#173177"
                            },"remark":{
                                "value":"'.$content['data']['remark']['value'].'",
                                "color":"#333333"
                            }        
                            }
                        }' ;
         $tempurl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$ACCESS_TOKEN;
          /*采用客服消息发送*/
         $text =  '{
                    "touser": "'.$content['touser'].'",
                    "msgtype":"text",
                    "text":
                    {
                     "content":"'.$content['data']['first']['value'].'\n------------------------------\n'
                    .$content['data']['keyword1']['value'].'\n------------------------------\n'
                    .$content['data']['keyword2']['value'].'\n------------------------------\n'
                    .$content['data']['remark']['value'].'"
                    }
                }';
        $texturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACCESS_TOKEN; 
            
          /*获取调用系统的get post 方法*/  
        load()->func('communication');
       
        $ret  = ihttp_post($texturl, $text);
        if(isset($ret['content']['errcode']) && $ret['content']['errcode']=='40001'){
             $ret  = ihttp_post($texturl, $text);
        }
        //logging_run($ret);
        return $ret;
         
    }
    public function save_send_notice_account($notice_type='', 
            $first='', 
            $keyword1='关键词1', 
            $keyword2='关键词2', 
            $remark='备注', 
            $touser='') {
        
        global $_GPC, $_W;
         $uniacid =  $this->_uniacid;  
         $gzhinfo = pdo_fetch("select * from ".tablename("kbwdl_config"). " where placeid=41 and uniacid='$uniacid' and module='kbwdl_shequzufang'");
         load()->func('logging');
         //logging_run($gzhinfo);
         if(!empty($gzhinfo['conf_value'])){
             $gzh = iunserializer($gzhinfo['conf_value']);
         }else{
             return false;
         }
         /*判断类型是否开启*/
         if(empty($notice_type) ||  $gzh[$notice_type]!=1){
             return false;
         }
            
         // logging_run($ACCESS_TOKEN);
         if(!empty($touser)){
             $content['touser'] = trim($touser);
         }else{
             $content['touser'] = $gzh['adminopenid'];
         }
         
         $content['template_id'] = $gzh['template_id'];
         $content['url'] =  '';
         $content['topcolor'] =  '#FF0000';
         $content['data']['first']['value'] = $first;
         $content['data']['keyword1']['value'] = $keyword1;
         $content['data']['keyword2']['value'] =$keyword2;
         $content['data']['remark']['value'] = $remark;
         /*采用客服消息发送*/
         $text =  '{
                    "touser": "'.$content['touser'].'",
                    "msgtype":"text",
                    "text":
                    {
                     "content":"'.$content['data']['first']['value'].'\n------------------------------\n'
                    .$content['data']['keyword1']['value'].'\n------------------------------\n'
                    .$content['data']['keyword2']['value'].'\n------------------------------\n'
                    .$content['data']['remark']['value'].'"
                    }
                }';
        /*$texturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACCESS_TOKEN; */
        /*保存到数据库 返回记录id 进行发送*/
        $save  =[ 
            'uniacid'=> $uniacid,
            'formids'=> iserializer($content),
            'openid' => 'kefumsg'.time()
        ] ;
        pdo_insert( 'kbwdl_formids', $save);
        
        return pdo_insertid();    
    }
    /**
     * 20180620 增加模板消息发送
     */
    public function _send_template_notice_old($openid, $page='',$form_id, $data=array())
    { 
        global $_GPC, $_W;
        load()->func('communication');     
        /*获取公众号access_token*/
        load()->classs('wxapp.account');
        if(empty($openid)){
            return ;
        }
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '".$this->_uniacid ."'" );       
        $accObj= new WxappAccount( $account);        
        $ACCESS_TOKEN = $accObj->getAccessToken( );         
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$ACCESS_TOKEN";
        $tempid = $this->module['config']['templateid'];
        $body = array('touser'=>$openid,'template_id'=>$tempid, 'form_id'=>$form_id,'emphasis_keyword'=>'');
        if(!empty($page)){
            $body['page'] = $page;
        }
        $body['data'] = $data;
        /*array('keyword1'=>array('value'=>'预约看房'),'keyword2'=>array('value'=>'请及时处理'));*/
        
         return  ihttp_post($url, json_encode($body));
    }
     public function _send_template_notice($openid, $page='',$form_id, $data=array())
    { 
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        load()->func('communication');     
        /*获取公众号access_token*/
        load()->classs('wxapp.account');
        if(empty($openid) || empty($form_id) ){
            return ;
        }
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '".$this->_uniacid ."'" );       
        $accObj= new WxappAccount( $account);        
        $ACCESS_TOKEN = $accObj->getAccessToken( );         
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$ACCESS_TOKEN";
        //$tempid = $this->module['config']['templateid']; /*新订阅消息 从前端提交模板id过来*/
        /*guest_kanfang \ guest_ask \ baobei_status  */
        $ret2 = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=61 and module='kbwdl_shequzufang'");
        $moban  =  iunserializer($ret2['conf_value']);
        switch ($form_id){
            case 'guest_kanfang':
                $form_id = $moban['guest_kanfang'];
                $sendbody = [
                    'thing5'=>['value'=> $data['keyword1']['value']],
                    'thing1'=> ['value'=> $data['keyword2']['value']],            
                ];
                break;
            case 'guest_ask':
                $form_id = $moban['guest_ask'];
                $sendbody = [
                    'phrase1'=>['value'=> '通过审核'],
                    'thing2'=> ['value'=> $data['keyword2']['value']], 
                    'date3'=>['value'=> date('Y年m月d日')],
                ];
                break;
            case 'baobei_status':
                $form_id = $moban['baobei_status'];
                $sendbody = [
                    'name1'=>['value'=>   $data['keyword2']['value'] ],
                    'phrase3'=>['value'=>str_replace( '经纪人客户：','',$data['keyword3']['value'][0] )]  , 
                    'phrase5'=>['value'=> $data['keyword4']['value']],
                    'phone_number2'=> ['value'=> str_replace('手机号：','',$data['keyword3']['value'][1] ) ],
                ];
                break;
            default:
                break;
        }
         
        $body = array('touser'=>$openid,'template_id'=>$form_id);
        if(!empty($page)){
            $body['page'] = $page;
        }
        $body['data'] = $sendbody; 
       
        /*array('keyword1'=>array('value'=>'预约看房'),'keyword2'=>array('value'=>'请及时处理'));*/
         load()->func('logging');
        //  logging_run($body);
         $ret =   ihttp_post($url, json_encode($body));
        // logging_run($ret);
         return $ret;
    }
    public function doPageIndex() { 
    // 接口一个名为"index"的接口
 
      $this->result(0, '', array('test' => $this->_uniacid)); //  响应json串
    }

    /*     * *
     * 二手 租房 商业房 详情
     */

    public function doPageHouseinfo() {
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        $uid = $_W['member']['uid'];
        $openid = $_W['openid'];
        $id = $_GPC['id'];
        $fileds = '*, 0+CAST(loyer AS CHAR) as loyer ';
        $sql = "SELECT $fileds  FROM " . tablename("kbwdl_house") . " where uniacid='$uniacid' and  id='$id'";
        $info = pdo_fetch($sql);
        if(empty($info)){
            /*没有获取到数据不操作*/
             $this->result(0, '', []);
        }
        /* 处理房源信息 获取腾讯实际播放地址 */
        preg_match('/<iframe(.*?)src="(.*?)"/', $info['description'], $arr);
        $info['vurl'] = $arr[2];
        $urlinfo = parse_url($arr[2]);
        if(!empty($urlinfo['query'])){
            $query = explode('&', $urlinfo['query']);
             $a2 = array();
                foreach ($query as $q)
                {
                    $a1 = explode('=', $q);
                    $a2[$a1[0]] = $a1[1];
                }
        }
        $info['videoid'] = $a2['vid'];
        $furl_real = '';
        if(!empty($info['videoid'])){
           $a3 = file_get_contents('https://vv.video.qq.com/getinfo?otype=json&appver=3.2.19.333&platform=11&defnpayver=1&vid='.$info['videoid']);
            // $a3 = file_get_contents('http://vv.video.qq.com/getinfo?vids='.$info['videoid'].'&platform=101001&charge=0&otype=json');
            $a3  = str_replace('QZOutputJson=', '', rtrim($a3,';'));
            $a3 = json_decode($a3, true);
            $fvkey = $a3['vl']['vi'][0]['fvkey'];
            $fn = $a3['vl']['vi'][0]['fn'];
            $furl = $a3['vl']['vi'][0]['ul']['ui'][0]['url'];
            $furl_real = $furl .$fn .'?vkey='.$fvkey;
        }
        $info['videoinfo'] = $furl_real;
        /* 结束腾讯视频获取 */
       /*获取自己上传的视频*/
        if(!empty($info['video']) ){
            $info['video'] = tomedia($info['video']);           
        }else{
            $info['video'] = '';
        } 
        /*封面图*/
        if(empty($info['thumb'])){
            $info['thumb'] =  'addons/kbwdl_shequzufang/style/images/house_face.jpg' ;
        }
        if (!empty($info['thumb_url'])) {
            $info['thumbs'] = iunserializer($info['thumb_url']);
            foreach ($info['thumbs'] as $key => $item) {
                $info['thumbs'][$key] = tomedia($item);
            }           
        }
        if (empty($info['thumbs'])) {
             /*把封面图加载进来*/
            $info['thumbs'][] = tomedia( $info['thumb']) ;           
        }
        /*兼容 重新组装 thumbs 数据 兼容 幻灯片组件*/
        foreach($info['thumbs'] as $thumb){
            $info['slides'][] = array(
                'url'=> "",/*这个是图片链接*/
                'thumb'=> $thumb,
            );
        }
         /*默认封面图*/
        $info['update_time'] = date('Y-m-d H:i:s', $info['update_time']);
        $params = pdo_fetchall("select * from ".tablename("kbwdl_param")." where houseid='$id' order by displayorder asc");
        foreach($params as $k => $p){
            $info['params'][] = $p;
        } 
             /**联系人信息*/
        $default_avatar = "/addons/kbwdl_shequzufang/style/images/get_avatar.png";
        $info['broker'] = array(
            'id' => 0,
            'avatar' => toimage($default_avatar),
            'nickname'=> $info['publish_name'],
            'mobile'=> $info['linkphone'],
            'company'=> '联系人',
        );
        /* 获取经济人 */
        $info['orgin_broker_id'] = $info['broker_id']; /*房源发布人的真实人*/
        $isremobile = 1;
        /*如果有指定经纪人 id 那么把发布人替换成此人 主要是海报分享扫码进来*/
        if(isset($_GPC['brokerid']) && (intval($_GPC['brokerid'])>0)){             
            $info['broker_id'] = intval($_GPC['brokerid']);
            $isremobile = 0;
        }
        if ($info['broker_id']) {
            $broker = pdo_fetch("select id,groupid,ecuid, nickname,openid,mobile,company,avatar,vtags from " . tablename("kbwdl_broker") . " where groupid > 0 and id='" . $info['broker_id'] . "'");
            if($broker){
                if (!strpos($broker['avatar'], "/")) {
                    $broker['avatar'] = $default_avatar;
                }
                $broker['avatar'] = toimage($broker['avatar']);
                /*显示房源发布的手机号时*/
                if($isremobile && $this->module['config']['system']['bindmobile']==2){
                    $broker['mobile'] = $info['linkphone'];
                }
             
                $info['broker'] = $broker;
            }
        }
        /*格式化数据*/
        $info = $this->_format_sechouse($info);
        if($this->module['config']['isduocity']==1){
            $info['area'] = $info['cityname'].'-'.$info['area'];
        }
        /*修正百度地图到腾讯地图*/
      if($info['mapinfo']){
         /*百度坐标转换为火星坐标 腾讯地图显示火星坐标 */  
          if(strlen($info['mapinfo'])<22){  
            $point = explode(",", $info['mapinfo']);
          
            $bd_lon  = $point[0]; 
            $bd_lat  = $point[1]; 
            $X_PI = M_PI * 3000.0 / 180.0;  
            $x = $bd_lon - 0.0065;  
            $y = $bd_lat - 0.006;  
            $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $X_PI);  
            $theta = atan2($y, $x) - 0.000003 * cos($x * $X_PI);  
            $lon = $z * cos($theta);  
            $lat = $z * sin($theta); 
            $info['mapinfo'] = $lon.",".$lat;   
          }
               
      }
        /*点击数*/
        if($id){
            pdo_update( 'kbwdl_house', array('onclick +='=>1) , array('id' => $id) ); 
        }
        /*浏览历史记录*/
        $houseid = intval($id);
        $yested = TIMESTAMP-24*3600;
        $fav = pdo_fetch("select id from ".tablename("kbwdl_favorite")." where ftype=1 and addtime>'$yested' and houseid='$houseid' and uniacid='$uniacid' and openid='$openid'");
        if(!empty($fav)){
           pdo_update(
                'kbwdl_favorite',
                array('hits +='=>1,'last_time' => TIMESTAMP) ,
                array('id' => $fav['id'])
            );       
        }else{
            $savedata  = array(
                'uid'=> $uid,
                'openid'=> $openid,
                'uniacid'=> $uniacid,
                'addtime' => TIMESTAMP,
                'houseid' => $houseid,
                'ftype' => 1,
                'hits'=>1,
                'acttype'=>'view',
                'last_time' => TIMESTAMP,
                'title' => $info['title'],
                'smalltext' => "{$info['village_name']} | {$info['room']}房{$info['hall']}厅{$info['garder']}卫 | {$info['superficie']}㎡ | {$info['loyer']}{$info['prix_unitaire']}"      
             );
             pdo_insert('kbwdl_favorite', $savedata);
        }
        /*发送管理员消息*/
        $this->_send_notice_account('view_notice' ,"【{$uid}】浏览房源" ,$info['title'] , "发布人：" .$info['publish_name'] , '房源浏览量 '.$info['onclick']);
            
        $this->result(0, '', $this->_format_show_item($info));
    }
     
    /**
     * 格式化前端显示 二手房 租房 商铺 生意转让
     */
    /*格式化输出参数到前端模板*/
      public  function _format_show_item($val , $ischarges=0, $groupid=0){
            $val['ischarges'] = $ischarges;
            $val['groupid'] = $groupid;
            /*默认房源类型的列表页 是二手房*/
            $val['moreurl'] = "../house/search?type=2";
            if($val['rent_type']==0 && $val['zhutype']==0){            
                /*二手房*/
                $val['item_address'] = $val['room'].'房'. $val['hall'].'厅 / '. 
                        $val['superficie'].'㎡ / '. $val['donner_sur'] .
                        ' / '.$val['storey'] ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =    $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit']) : '';
                $val['quan'] = $val['quan'] ? $val['quan'] : $val['village_name'];
                if($val['quan'] =='-'){
                     $val['quan'] =  $val['village_name'];
                }
                $val['item_area'] =  $val['area'] .' '. $val['quan'] ;
                 $val['item_time'] = '';
                $val['showtag'] = 1; /*显示标签*/
                if($ischarges==1){ /*分销处理*/
                    if($groupid==0){
                        $val['price_label'] = '售价';
                    }else{
                       $val['price_label'] = '佣'; 
                       $val['item_price'] = $val['employee'] ? $val['employee'] : $val['item_price'];
                    }
                }
               
            }else if($val['rent_type']==2 && $val['zhutype']==0){
                 $val['moreurl'] = "../house/zhu?rent=2&zhutype=2";
                /*租房*/
                $val['item_address'] = $val['room'].'房'. $val['hall'].'厅 / '. $val['superficie'].'㎡   ' ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =   '';/*  $val['menpai'];*/
                $val['quan'] = $val['quan'] ? $val['quan'] : $val['village_name'];
                if($val['quan'] =='-'){
                     $val['quan'] =  $val['village_name'];
                }
                $val['item_area'] =  $val['area'] .' '. $val['quan'] ;
                 $val['item_time'] = '';
                 $val['showtag'] = 1; /*显示标签*/
                if($ischarges==1){ /*分销处理*/
                    if($groupid==0){
                        $val['price_label'] = '租金';
                    }else{
                       $val['price_label'] = '佣'; 
                       $val['item_price'] = $val['employee'] ? $val['employee'] : $val['item_price'];
                    }
                }
            }else if( $val['zhutype']==1){
                 $val['moreurl'] = "../house/xie?rent=".$val['rent_type']."&zhutype=1";
                /*写字楼 */
                $val['item_address'] = $val['area'].'  '. $val['quan'] .'  '.  $val['superficie'].'㎡   ' ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =   ''  ; 
               
                $val['item_area'] =   $val['village_name'];
                $val['item_time'] =   $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit']) : '';
                if($val['rent_type']==0){
                    $val['item_time'] = '单价 '.$val['item_time'] ;
                }else{
                     $val['item_time'] = '租金 '.$val['item_time'] ;
                }
                $val['showtag'] = 0; /*显示时间*/
            }else if( $val['zhutype']==2){
                 $val['moreurl'] = "../house/sp?rent=".$val['rent_type']."&zhutype=2";
                /*商铺 */
                $val['item_address'] =  $val['area'].$val['quan'] .'  '.  $val['superficie'].'㎡   ' ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =   ''  ; 
               
                $val['item_area'] = $val['village_name'];
                $val['item_time'] =   $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit']) : '';
                if($val['rent_type']==0){
                    $val['item_time'] = '单价 '.$val['item_time'] ;
                }else{
                     $val['item_time'] = '租金 '.$val['item_time'] ;
                }
                $val['showtag'] = 0; /*显示时间*/
                if($ischarges==1){ /*分销处理*/
                    if($groupid==0){
                        $val['price_label'] = '售价';
                    }else{
                       $val['price_label'] = '佣'; 
                       $val['item_price'] = $val['employee'] ? $val['employee'] : $val['item_price'];
                    }
                }
            }else if( $val['zhutype']==3){
                 $val['moreurl'] = "../house/syi?rent=".$val['rent_type']."&zhutype=3";
                /*生意转让 */
                $val['item_address'] = $val['area'].'  '. $val['quan'].  $val['superficie'].'㎡   ' ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =   '转让费 '.$val['dong'].'万'  ; 
               
                $val['item_area'] =   $val['village_name'];
                $val['item_time'] =   $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit'])  : '';
                $val['item_time'] = '租金'. $val['item_time'];
                $val['showtag'] = 0; /*显示时间*/
            }else if( $val['zhutype']==4){
                /*求租求购 */
                $val['item_address'] = $val['village_name']  ;
                $val['item_price'] =  $val['tags'][1]  ;
                $val['item_per'] =    '面积：'.$val['tags'][0]   ; 
               
                $val['item_area'] =  $val['area'].'  '. $val['quan'] ;
                $val['item_time'] =   $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit'])  : '';
                $val['item_time'] =  $val['room'].'房'. $val['hall'].'厅'. $val['garden'].'卫  ' ;
                $val['showtag'] = 0; /*显示时间*/
            }else if($val['zhutype'] ==7){
                /*厂房*/
                     $val['moreurl'] = "../house/xie?rent=".$val['rent_type']."&zhutype=7";
                /*写字楼 */
                $val['item_address'] = $val['area'].'  '. $val['quan'] .'  '.  $val['superficie'].'㎡   ' ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =   ''  ; 
               
                $val['item_area'] =   $val['village_name'];
                $val['item_time'] =   $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit']) : '';
                if($val['rent_type']==0){
                    $val['item_time'] = '售价 '.$val['item_time'] ;
                }else{
                     $val['item_time'] = '租金 '.$val['item_time'] ;
                }
            } else if($val['zhutype'] == 8){
                /*厂房*/
                     $val['moreurl'] = "../house/xie?rent=".$val['rent_type']."&zhutype=7";
                /*写字楼 */
                $val['item_address'] = $val['area'].'  '. $val['quan'] .'  '.  $val['superficie'].'㎡   ' ;
                $val['item_price'] =  $val['loyer'] .  $val['prix_unitaire'];
                $val['item_per'] =   ''  ; 
               
                $val['item_area'] =   $val['village_name'];
                $val['item_time'] =   $val['perprice'] ? ($val['perprice'] .  $val['perprice_unit']) : '';
                if($val['rent_type']==0){
                    $val['item_time'] = '售价 '.$val['item_time'] ;
                }else{
                     $val['item_time'] = '租金 '.$val['item_time'] ;
                }
            }
           return $val; 
        }
    /**
     * 格式化二手房房源
     * @param type $val
     */
    public function _format_sechouse($item) {
        $val = $item;
        if (empty($val['thumb'])) {
            $val['thumb'] = 'addons/kbwdl_shequzufang/style/images/house_face.jpg';
        }
        if((!strpos($val['thumb'],'mages') ) && (!strpos($val['thumb'],'weihouse'))){
            $val['thumb'] = 'addons/kbwdl_shequzufang/style/images/house_face.jpg';
        }
        $val['thumb'] = toimage($val['thumb']);

	    $s = max(1,$val['superficie'] ); 
            
       if($val['loyer']==0){
             $val['loyer'] =  '面议' ;
             $val['prix_unitaire'] = '';
             $val['first_price'] = '-';
             $val['perprice'] = '-';
        }else{
            $val['prix_unitaire'] = rtrim($val['prix_unitaire'], '元');
            $val['perprice'] = '-';
            $val['first_price'] =  "-";
            if(is_numeric($val['loyer'])){
                $val['perprice'] =  ceil($val['loyer']*10000 / $s);                
                $val['first_price'] = ceil($val['loyer']*40/100); 
            } 
        } 
        $val['infotype'] =  $val['rent_type']==2? '租': '售';
        /*日租房*/
        if($val['rent_type']==2 && $val['zhutype']==0 && $val['dong']=='日租'){
            if(is_numeric($val['loyer'])){
                $val['prix_unitaire'] = '元/日'; 
            }
        }
        if($val['rent_type']==2 && $val['zhutype']==0 && $val['dong']=='年租'){
            if(is_numeric($val['loyer'])){
                $val['prix_unitaire'] = '元/年'; 
            }
        }
        /*租房 押金*/
        if($val['rent_type']==2 && $val['zhutype']==0){
            $val['danyuan'] = empty($val['danyuan'])? '整租':$val['danyuan'];
            $val['dong'] = empty($val['dong'])? '月租':$val['dong'];
        }
        /*$val['perprice'] = '-';*/
        $val['perprice_unit'] = '元/㎡';
        /*如果是写字楼，商铺 ，生意 算出的是 元/㎡/月*/
        if($val['rent_type']==2 && ($val['zhutype'] <4)){
             if(is_numeric($val['loyer'])){
                $val['perprice'] = ceil($val['loyer'] / $s);
             } 
            $val['perprice_unit'] =  '元/㎡/月' ;
        }
        /*厂房出租*/
       if($val['rent_type']==2 && ($val['zhutype'] ==7 )){
             if(is_numeric($val['loyer'])){
                $val['perprice'] = ceil($val['loyer'] / $s);
             } 
            $val['perprice_unit'] = '';/* '元/㎡/月'*/;
        } 
        /*仓库出租*/
        if($val['rent_type']==2 && ($val['zhutype'] ==8 )){
             if(is_numeric($val['loyer'])){
                $val['perprice'] = ceil($val['loyer'] / $s);
             } 
            $val['perprice_unit'] = '';/* '元/㎡/月'*/;
        }   
        /*商铺出租*/
        if($val['rent_type']==2 && ($val['zhutype']==2)){
             if(is_numeric($val['loyer'])){
                 $val['perprice'] = ceil($val['loyer'] / $s /30);
             }
            $val['perprice_unit'] = '元/㎡·天';
            $val['infotype'] =   '铺';
        }
       if($val['rent_type']==0 ){
           if($this->module['config']['system']['layertype']==2){
               $val['storey'] = $val['storey'].'层';
           }else{
            /*二手房 楼层*/
            $storey = intval($val['storey']);
            $mid =  max($val['total_storey'],6) /2;
           if($storey>0){
             $val['storey'] = '低层';
             }
              if($storey>($mid-2)){
                 $val['storey'] = '中层';
             }
              if($storey>($mid+2)){
                 $val['storey'] = '高层';
             } 
           }
       }
       
        if($val['zhutype']==2){
            /*商铺没有装修信息*/
             $val['traveaux_finition'] = '';
        }
         /*生意租转*/
        if($val['rent_type']==0 && ($val['zhutype']==3)){
             if(is_numeric($val['loyer'])){
                $val['perprice'] =  ceil ($val['loyer'] / $s /30) ;
             }
            $val['perprice_unit'] = '元/㎡·天';
            $val['infotype'] =   '转';
            if(empty($val['dong'])){
                $val['dong'] = '面议';
            }else{
                 $val['dong'] =  $val['dong'];
            }
        }
        /*首付比例*/
        $perbill = $val['qq']? $val['qq']: 40;
        $val['bill'] = $perbill;
        $val['billpay'] = $val['loyer']* $perbill/100;
    
        $val['quan'] = $val['quan'] ? $val['quan'] : '-';
	
        $val['refresh_time'] = $val['refresh_time'] ? $val['refresh_time'] : $val['add_time'];
        if ($val['refresh_time'] > $val['add_time']) {
            $val['add_time'] = $val['refresh_time'];
        }
        $val['add_time'] = date('Y-m-d H:i', $val['add_time']);
        $val['refresh_time'] = date('Y-m-d H:i', $val['refresh_time']);
        /* 标签 */
        $tags = $val['disposition'];
        $val['tags_all'] = 
        $val['tags'] =   array( $val['infotype'],$val['house_type'] ?$val['house_type']:'' , $val['traveaux_finition']?$val['traveaux_finition']:'');
        $tag = [];
        if(!empty($tags)){
            $tag = explode(",", $tags);
            $val['tags_all'] = $tag;
            $tmp = array();             
                foreach($tag as $kk=> $vv){
                    if($kk>3){ break; }
                    if(!empty($vv)){
                        array_push($tmp, $vv);
                    }
             }
            $val['tags'] = $tmp;
        }
        /*厂房和 仓库 的标签 显示 类型和 */
         if($val['zhutype']==7 || $val['zhutype']==8){
            $val['tags'] = [$val['house_type'], $val['danyuan'],$val['dong'] ];  
            $val['perprice'] = '';
            $cg = [ '未知', "单层", "多层","立体","简仓","露天"];
            if(isset($cg[$val['storey']])){
                $val['storey'] = $cg[$val['storey']];
            }
            
         }
        if ($val['zhutype'] == '3') {
            /* 生意转让 */
            $tmp = explode(',', $val['disposition']);
            $val['hangye'] = $tmp[0];
            $val['jingyin'] = $tmp[1];
        }
        $val['helpinfo'] = '温馨提示：请去电时说明在《'.$this->module['config']['shopname'].'》上看到，谢谢！';
       
        /*发布类型*/
        $val['pushtype'] = $val['ptype']==1? '个人': '中介';
        /*开启所有电话统一*/
        if($this->module['config']['isallphone']==1){
            $val['linkphone'] = $this->module['config']['phone'];
            $val['broker']['mobile'] = $val['linkphone'];
        }
        /*佣金*/
        if(empty($val['employee'])){
            $val['employee'] = '';
        }
        return $val;
    }
    public function _checkPostContent($data){
                /*鉴别内容*/
        /*关闭时不用*/
        if($this->module['config']['closecheck']==1){
            return true;
        }
        $str = implode("", $data);
        load()->func('communication');     
        /*获取小程序access_token*/
        load()->classs('wxapp.account');
            
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '".$this->_uniacid ."'" );       
        $accObj= new WxappAccount( $account);        
        $ACCESS_TOKEN = $accObj->getAccessToken( );  
        $WxApi = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={$ACCESS_TOKEN}";
        /*JSON_UNESCAPED_UNICODE 确保json数据不被编码*/
        $ret = ihttp_post($WxApi,  json_encode(array('content'=>$str ),JSON_UNESCAPED_UNICODE));
        if($ret['content']){
             $ret = json_decode( $ret['content'], true);
            
             if(isset($ret['errcode']) && $ret['errcode'] &&  $ret['errcode'] == 87014 ){
                  $this->result(404, '内容安全监测失败'.$ret['errcode'], $ret);
             }
        }else{
            return true;
        }
    }
    /**
     * 插入二手房前台提交的数据
     */ 
    public function doPagePostsechouse()
    {
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        $uid = $_W['member']['uid'];
        $openid = $_W['openid'];
        $fileds = array('title', 'area', 'quan', 'village_name', 'house_sno','menpai',
            'room', 'hall', 'garder', 'superficie', 'loyer', 'prix_unitaire','danyuan',
            'prix_unitaire', 'house_type', 'zhutype', 'dong','isdelete','qq','firstpay',
            'traveaux_finition', 'storey', 'total_storey', 'donner_sur','disposition',
            'build_age', 'description', 'publish_name','linkphone', 'vrurl','video');
        foreach($fileds as $field){           
            $data[$field] = $_GPC[$field] ;
        }
        $this->_checkPostContent($data);
            
        /** * 如果是多城市         */
        if($this->module['config']['isduocity']==1){
            
            $data['cityname'] = $data['area'];
            $data['area'] = $data['quan'];
            $data['quan'] = '';
            $data['city_id'] = pdo_fetchcolumn("select id from ".tablename('kbwdl_area')." where name='".$data['cityname']."' and uniacid='$uniacid'");

        }
        /*图片*/
        if(!empty($_GPC['thumbs'])){
            $thumb =  explode(',',$_GPC['thumbs'] );
            $data['thumb_url'] = serialize($thumb);
            $data['thumb'] = $thumb[0];
        }
        /*地址解析成坐标*/
        if(!empty($_GPC['latlon'])){
             $data['mapinfo'] =  $_GPC['latlon'];
        }else{
             $data['mapinfo']  = "";
            /*$data['mapinfo'] = $this->_address_to_point($this->module['config']['cityname']. $data['area']. $data['village_name']);
             * 
             */
        }
       
        /* 特色 */
        if (isset($_GPC['disposition']) && !empty($_GPC['disposition'])) {
            $data['disposition'] = $_GPC['disposition'];
        }
        /* 处理经纪人发布 */
        $data['ptype'] = 0;
        $broker = pdo_fetch("select * from " . tablename("kbwdl_broker") . " where openid='$openid' and uniacid='$uniacid'");
        if(empty($broker['mobile']) || ($broker['disabled'] ==1 ) || ($broker['ischecked']==0)){
             $this->result(1, '资料未审核通过',$data);
             exit;
        }
        if(!$this->_checkIsMobile($broker['mobile'])){
             $this->result(1, '绑定的手机号格式错误', $data);
             exit;
        }
        if ($broker['id'] > 0) {
            $data['broker_id'] = $broker['id'];
            $data['broker_name'] = $openid;  
            if($broker['groupid']==0){
                $data['ptype'] = 1;/*个人发布*/
            }
        } else {
            $data['broker_id'] = 0;
            $data['broker_name'] = $openid;
             $data['ptype'] = 1;/*个人发布*/
        }
  
       
        $data['rent_type'] = $_GPC['rent_type'];
        if (empty($_GPC['prix_unitaire'])) {
            $data['prix_unitaire'] = $_GPC['rent_type'] == 2 ? '元/月' : '万';
        } else {
            $data['prix_unitaire'] = $_GPC['prix_unitaire'];
        }
        $data['uniacid'] = intval($uniacid);
        $data['endtime'] = strtotime("+15 day");
        
        $data['update_time'] = TIMESTAMP;
        $data['refresh_time'] = TIMESTAMP;
        $data['description'] =  htmlspecialchars_decode($data['description']);
        if($data['prix_unitaire'] == '元/㎡/月'){
            $data['danyuan'] = $data['loyer'];
            $data['menpai'] = $data['prix_unitaire'] ;
            $data['loyer'] = $data['danyuan']* $data['superficie'];
            $data['prix_unitaire'] = '元/月';
        } 
        if($data['rent_type']==2 && ($data['zhutype']==0)){
            if(empty($data['danyuan'])) {
                 $data['danyuan']  = '整租';
            }            
            if(empty($data['dong'])) {
                 $data['dong'] = '月租';
            }
        }
           /* $data['menpai'] = '' ;*/
            
        $data['loyer'] = sprintf('%.2f', $data['loyer']);
       
        $data['iscompany'] = 9; /*前台发布*/
        $data['permission'] = 0;
        /*修改或者添加*/
        $id = intval($_GPC['id']);
        if (empty($id)) {
            $data['add_time'] = TIMESTAMP;
            $data['refresh_time'] = TIMESTAMP;
            $data['isonline'] = 1;
              /*处理发布审核问题$this->module['config']*/
            if($this->module['config']['system']['needcheck']==1){
                $data['isdelete'] = 1;
                /*经纪人等级 房源不需要审核*/
                if(isset($broker['groupid']) && $broker['groupid']>0){
                    $data['isdelete'] = 0;
                }            
                
            } else{
                $data['isdelete'] = 0;
            }
            $ret = pdo_insert('kbwdl_house', $data);
            $id = pdo_insertid();
            /* 扣除积分 */
            if ($_GPC['needpay'] == 1 && $_GPC['need_credit']) { /* 可以扣积分 置顶操作 */

                /* 创建充值记录 */
                load()->model('mc');
                /* 代金券和折扣券的兑换记录, */
                $credit = $_GPC['need_credit'];
                mc_credit_update($uid, 'credit2', -$credit, array($uid, '发布房源使用余额：' . $credit));
                pdo_insert("kbwdl_actlog", array(
                    'actname' => 'publish',
                    'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
                    'money' => $credit, 'ecuid' => $uid, 'acttype' => 3, 'isadd' => 0,
                    'infoid' => $id, 'uniacid' => $uniacid,
                    'note' => '发布房源使用余额'
                ));
            }
            /* ====== */
        } else {
            unset($data['isdelete']);
            $ret = pdo_update('kbwdl_house', $data, array('id' => $id));
        }
        /*发布信息给管理员*/
        $this->_send_notice_account('send_notice','有新的房源发布', $_GPC['title'],  "户型".$_GPC['room'].'房'.$_GPC['house_type'], '房源ID '.$id);
            /*统计数量*/
        $info = pdo_fetch("select broker_id,broker_name from ".tablename("kbwdl_house")." where id='$id' and uniacid='$uniacid'");
        $this->count_broker_send_num($info['broker_id'],$info['broker_name']);
        $this->result(0, '保存成功', $data);
    }
    
    /**
     * 返回查询数据的配置参数
     */
    public function doPageSearchkey()
    {
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        $uid = $_W['member']['uid'];
        $openid = $_W['openid'];  
        $p = [];
        /**/
        $sql = 'SELECT `settings` FROM ' . tablename('uni_account_modules') . ' WHERE `uniacid` = :uniacid AND `module` = :module';
        $settings = pdo_fetchcolumn($sql, array(':uniacid' => $uniacid, ':module' => 'kbwdl_shequzufang'));
        $sec =   iunserializer($settings);
            
        /*查询商圈*/
        $default_quan = [];
            $quan = pdo_fetchall("select * from ".tablename("kbwdl_area")." where uniacid='$uniacid' and type=2 and disabled=0 order by orderid desc ,id desc");
            if(!empty($quan)){
                $tmp = array();
                foreach($quan as $key=>$q){
                     $tmp[$q['area']][] = $q['name'];
                }            
                $default_quan   = $tmp ;
            
            } 
        if($sec['isduocity']==1){
                $city_str = '';
                  /*查询个人设置的,暂时不能实现按用户当前选择的城市默认区域。*/
                $dsql = "";
                    $ucity = pdo_fetchcolumn("select city_id from ".tablename("kbwdl_share_user")." where uniacid='$uniacid' and openid='$openid'");
                    if($ucity){
                            $dsql = " and id='$ucity'";
                    }
                /*增加多城市 只发布到自己的城市*/
                $sql = "select * from ". tablename("kbwdl_area")." where uniacid='$uniacid' and type='4' and disabled=0 $dsql " ; 
                /*城市区域*/
                $tmp2 = $tmp = [];
                $allareas =  pdo_fetchall("select placeid, conf_value from ".tablename('kbwdl_config')." where confkey='areas' and uniacid='$uniacid' ");
                foreach($allareas as $k=>$v){
                    $tmp2 = form_element::_option($v['conf_value']);
                    if($tmp2){
                        foreach($tmp2 as $kk=>$vv){
                            $tmp[$v['placeid']][] = $vv;
                        }
                    }
                }
                /*所有城市 和它 的区域信息*/
                $all = pdo_fetchall($sql );
                $dot = "";
                foreach($all as $key=>$val){
                   $city_str.= $dot. $val['name'].'|'.$val['name'];
                   $dot = ",";
                   $pid = '8'.$val['id'];
                   $p['quan'][$val['name']] = $tmp[$pid] ;
                }   
               
                /*覆盖 其他参数*/
                $default_city = pdo_fetchcolumn("select conf_value from ".tablename("kbwdl_config")." where uniacid='$uniacid' and placeid='800'  and confkey='default_city'");
                $ucity = 0;
                if($default_city){
                  
                    $pid = '8'.$default_city;
                    $city_params = pdo_fetchall("select confkey, conf_value from ".tablename("kbwdl_config")." where uniacid='$uniacid' and placeid='$pid'");
                    foreach($city_params as $key => $val){
                        if(!empty($val['conf_value'])){
                        $sec[$val['confkey']] = $val['conf_value'];
                        }
                    }
                    
                }
                if($_GPC['isend']==1   ){ 
                    /*发布房源时 特殊处理，城市 设置为区域*/
                     $p['areas'] = form_element::_option($city_str);
                }else{
                    $p['areas'] = form_element::_option($sec['areas']);  
                    $p['quan'] = $default_quan;
                }
        }else{
            $p['areas'] = form_element::_option($sec['areas']);
           /*查询商圈*/
            $quan = pdo_fetchall("select * from ".tablename("kbwdl_area")." where uniacid='$uniacid' and type=2 and disabled=0 order by orderid desc ,id desc");
            if(!empty($quan)){
                $tmp = array();
                foreach($quan as $key=>$q){
                     $tmp[$q['area']][] = $q['name'];
                }            
               foreach ($p['areas'] as $k=>$pv){
                    $p['quan'][$k] = $tmp[$pv];
                }
            } 
        }
        /* 价格类型 */
            $p['zu_price'] = form_element::_option($sec['search_zhu_price']);
        /*根据类型获取不同价格类型*/
        if (intval($_GPC['type'] == 2)) {/*租房*/
            $p['price'] = form_element::_option($sec['search_zhu_price']);
        } elseif ($_GPC['type'] == 1) {/*新房*/
            $p['price'] = form_element::_option($sec['search_newhouse_price']);
        } elseif($_GPC['type'] == 10){ /*写字楼出 租*/
            $p['price'] = form_element::_option($sec['search_xie_sou_price']);
        } elseif($_GPC['type'] == 12){ /*写字楼出售*/
            $p['price'] = form_element::_option($sec['search_xie_zhu_price']);
        } elseif($_GPC['type'] == 20){ /*商铺出售*/
            $p['price'] = form_element::_option($sec['search_sp_sou_price']);
        } elseif($_GPC['type'] == 22){ /*商铺出售*/
            $p['price'] = form_element::_option($sec['search_sp_zhu_price']);
         } elseif($_GPC['type'] == 30){ /*生意转让*/
            $p['price'] = form_element::_option($sec['search_syi_sou_price']);
        }elseif($_GPC['type'] == 70 || $_GPC['type'] == 80 ){ /*厂房仓库出租*/
            $p['price'] = form_element::_option($sec['search_xie_sou_price']);
        } elseif($_GPC['type'] == 72  || $_GPC['type'] == 82){ /*厂房仓库出租*/
            $p['price'] = form_element::_option($sec['search_xie_zhu_price']);
        }else{/*二手房*/
            $p['price'] = form_element::_option($sec['search_sec_price']);
        }
        $p['housetype'] = form_element::_option($this->_forms['housetype']);
    
        $p['sptype'] = form_element::_option($this->_forms['sptype']);
        $p['chaoxiang'] = form_element::_option($this->_forms['chaoxiang']);
        $p['zhaungxiu'] = form_element::_option($this->_forms['zhaungxiu']);
        $p['disposition'] = form_element::_option($this->_forms['disposition']);
        $p['rent_zhu'] = form_element::_option($this->_forms['rent_zhu']);
        $p['louceng'] = form_element::_option($this->_forms['louceng']);
          /*厂房*/
         $p['rent_changfang'] = form_element::_option($this->_forms['rent_changfang']);
         $p['changfang_type'] = form_element::_option($this->_forms['changfang_type']);
         $p['changfang_jiegou'] = form_element::_option($this->_forms['changfang_jiegou']);
          $p['cangku_used'] = form_element::_option($this->_forms['cangku_used']);
           $p['oldage'] = form_element::_option($this->_forms['oldage']);
         /*仓库类型*/
         $p['cangku_type'] = form_element::_option($this->_forms['cangku_type']);
        /* 行业，行业类型 */
        $p['hangye'] = form_element::_option($this->_forms['hangye']);
        $p['jingyin'] = $this->_forms['jingyin'];
        $p['charges_step']=   form_element::_option($this->_forms['charges_step'],',','|', true);
      

        $years = date('Y');
        $start = 1987;
        $p['years']  = array();
        for ($i = 0; $i < ($years - $start); $i++) {
            array_push($p['years'],  $years - $i);
        }
         
        $p['sufix'] = form_element::_option($sec['search_sec_sufix']);
        $p['room'] = array( '一房'=> 1, '两房'=> 2, '三房'=> 3, '四房'=> 4, '四房以上'=> 5);
        $p['mainhouse'] = $this->other['hxtype'];
        $p['order'] = array('默认排序'=>1,'单价由低到高'=>2,'单价由高到低'=>3,'开盘时间顺序'=>4,'开盘时间倒序'=>5);
        $p['housetags']= $this->other['housetags'];
        $p['projectTypes'] = $this->other['projectTypes'];
        $p['opentime'] = $this->other['opentime'];
        /*二手房房屋时间*/
        $p['houseyears'] = array('2年内'=>1,'2-5年'=>2 ,'5-10年'=>3,'10年上'=>4);
        $p['ptype'] = array('个人'=>1,'经纪人'=>2);
        $p['secorder'] = array('发布时间最新'=>1, '更新时间最新'=>2, '价格从高到低'=>3);
        /*租房的类型*/
        $p['zhumethod'] = array('整租'=>1, '合租'=>2);
        $p['zhudays'] = array('年租'=>1, '月租'=>2,'日租'=>3);
        /**
         * 获取列表可用模块
         */
        $ret2 = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=11 and module='kbwdl_shequzufang'");
        $confmenu = iunserializer($ret2['conf_value']);
        $block = array(
          'house_nav_newhouse'=>array( 'name'=> '新房', 'url'=> '../newshop/search', 'opentype'=> 'redirect','tags'=>0 ),
          'house_nav_sec'=> array( 'name'=> '出售', 'url'=> '../house/search?rent=0&zhutype=0', 'opentype'=> 'redirect' ,'tags'=>0),
          'house_nav_zhu'=> array(  'name'=> '租房', 'url'=> '../house/zhu?rent=2&zhutype=2', 'opentype'=> 'redirect','tags'=>1 ),
          'house_nav_xie_zhu'=> array(  'name'=>'写字楼出租', 'url'=> '../house/xie?rent=2&zhutype=1', 'opentype'=> 'redirect' ,'tags'=>2 ),
          'house_nav_xie_sale'=> array(  'name'=> '写字楼出售', 'url'=> '../house/xie?rent=0&zhutype=1', 'opentype'=> 'redirect' ,'tags'=>2 ),
          'house_nav_sp_zhu'=> array(  'name'=> '商铺出租', 'url'=> '../house/sp?rent=2&zhutype=2', 'opentype'=> 'redirect','tags'=>3  ),
          'house_nav_sp_sale'=> array(  'name'=> '商铺出售', 'url'=> '../house/sp?rent=0&zhutype=2', 'opentype'=> 'redirect' ,'tags'=>3 ),
          'house_nav_syi_sale'=>  array( 'name'=> '生意转让', 'url'=> '../house/syi?rent=0&zhutype=3', 'opentype'=>'redirect' ,'tags'=>4 ),
         'house_nav_changfang_sale'=>  array( 'name'=> '厂房出售', 'url'=> '../house/changfang?rent=0&zhutype=7', 'opentype'=>'redirect' ,'tags'=>7 ),
         'house_nav_cangku_sale'=>  array( 'name'=> '仓库出售', 'url'=> '../house/cangku?rent=0&zhutype=8', 'opentype'=>'redirect' ,'tags'=>7 ),
        'house_nav_changfang_zhu'=>  array( 'name'=> '厂房出租', 'url'=> '../house/changfang?rent=2&zhutype=7', 'opentype'=>'redirect' ,'tags'=>8 ),
         'house_nav_cangku_zhu'=>  array( 'name'=> '仓库出租', 'url'=> '../house/cangku?rent=2&zhutype=8', 'opentype'=>'redirect','tags'=>8  )
        
        );
        $navbtn =  array();
        foreach ($block as $key =>$v){
            if( $confmenu[$key] ==1 ){
                $navbtn[] = $v;
            }
        }
        $p['house_nav_block'] = $navbtn;
        /*end*/
        
        $this->result(0, '', $p);
    }
 
    /**
     * 房源列表接口
     */
    public function doPageSearch()
    { 
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        $uid = $_W['member']['uid'];
        $openid = $_W['openid'];
        /**/
        $search['keyword'] = trim($_GPC['keyword']);
        $search['area'] = trim($_GPC['area']);
        $search['minprice'] = trim($_GPC['minprice']);
        $search['maxprice'] = trim($_GPC['maxprice']);
        $search['minsufix'] = trim($_GPC['minsufix']);
        $search['maxsufix'] = trim($_GPC['maxsufix']);
        $search['room'] = trim($_GPC['room']);
        $search['isjingping'] = intval($_GPC['isjingping']);
        $search['istop'] = intval($_GPC['istop']);
        $rent_type = intval($_GPC['rent_type']);
        if (isset($_GPC['rent_type'])) {
            $rent_type = intval($_GPC['rent_type']);
        }
        /*zhutype*/
        $search['zhutype'] = trim($_GPC['zhutype']);
         

        $condition = " uniacid='$uniacid' and isonline=1 and isdelete=0 and rent_type='$rent_type'";
        /* 指定bid 表示查询经纪人的房源，isbroker =1 通过openid查询房源 */
        if (isset($_GPC['isbroker']) && $_GPC['isbroker'] == 1) {
            $brokerid = intval($_GPC['bid']);
            if ($brokerid > 0) {
                $condition = " uniacid='$uniacid' and broker_id='$brokerid' and rent_type='$rent_type'";
            } else {
                $brokerid = pdo_fetchcolumn("select id from " . tablename("kbwdl_broker") . " where openid='$openid' and uniacid='$uniacid'");
                if ($brokerid > 0) {
                    $condition = " uniacid='$uniacid' and broker_id='$brokerid' and rent_type='$rent_type'";
                } else {
                    $condition = " uniacid='$uniacid' and broker_name='$openid' and rent_type='$rent_type'";
                }
            }
        }
        /* 分页参数 */
        $page = max(1, $_GPC['page']);
        $pagesize = 10;
        $startlimit = ($page-1)* $pagesize;
           
        if(!empty($search['keyword'])){
            $condition .= " and (`title` like '%{$search['keyword']}%' or `area` like '%{$search['keyword']}%' or `village_name` like '%{$search['keyword']}%')";
        }
        if(!empty($search['area'])){
            $condition .= " and area='{$search['area']}'";
        }
        if(!empty($search['minprice'])){
            $condition .= " and loyer>='{$search['minprice']}'";
        }
        if(!empty($search['maxprice'])){
            $condition .= " and loyer<='{$search['maxprice']}'";
        }
        if(!empty($search['minsufix'])){
            $condition .= " and superficie>='{$search['minsufix']}'";
        }
        if(!empty($search['maxsufix'])){
            $condition .= " and superficie<='{$search['maxsufix']}'";
        }
        if(!empty($search['room'])){
            $condition .= " and room='{$search['room']}'";
        }
        if($search['isjingping'] == 1){
             $condition .= " and isjingpin='{$search['isjingping']}'";
        }
        if(!empty($search['zhutype'] )){
             $condition .= " and zhutype in ({$search['zhutype']})";
        }
        /*置顶设置*/
        if($search['istop']==1){
            $condition .= " and istop='1' ";
            $pagesize = 1000;
        }else{
            if(!isset($_GPC['isbroker'])){
                $condition .= " and istop='0' ";
            }
        }
        $fileds =  $this->_query_sechouse_field();

        $sql = "SELECT $fileds  FROM " . tablename("kbwdl_house") . " where $condition order by update_time desc ,refresh_time desc limit $startlimit, $pagesize";
        $items = pdo_fetchall($sql);
        if (!empty($items)) {
            foreach ($items as $key => $val) {
                $items[$key] = $this->_format_sechouse($val);
            }
            $this->result(0, "查询成功 $sql", $items);
        } else {
            $this->result(0, "$sql", $items);
        }
    }
    /*二手房查询列表的字段*/
    public function _query_sechouse_field(){
        return   ' id,title, 0+CAST(loyer AS CHAR) as loyer,traveaux_finition,donner_sur,area,quan,prix_unitaire,storey,
            superficie,total_storey,update_time,endtime,house_type,isonline,isdelete,company,broker_id,publish_name,employee,
            isjingpin,ishot,istop,show_jiaji,show_you,show_hight,disposition,zhutype,dong,ptype,danyuan, menpai,
            thumb,room,hall,garder,village_name,build_age ,rent_type,add_time,onclick,refresh_time,video ';
    }
     
    /**
     * 更换城市接口
     */
    
    public function doPageChangeCity(){
       global $_GPC, $_W;
        $uniacid  = $this->_uniacid;
        $openid  = $_W['openid'];
        $uid  = $_W['member']['uid'];  
        $cityid = intval($_GPC['cityid']);
        $ret = pdo_fetch("select id, city_id from ".tablename("kbwdl_share_user"). " where uniacid='$uniacid' and openid='$openid'");
        if($ret){
            pdo_update("kbwdl_share_user", ['city_id'=> $cityid], array('id'=> $ret['id']));
        }else{
            $save['addtime'] = TIMESTAMP;
            $save['openid']= $openid;
            $save['uniacid'] = $uniacid;
            $save['city_id'] = $cityid;
            pdo_insert("kbwdl_share_user", $save);
        }
       // pdo_query("update ".tablename('kbwdl_config')." set conf_value='$cityid' where uniacid='$uniacid' and placeid='800' and confkey='default_city'");
        $this->result(0, $cityid ,  []);
    }
    /**
     * 更新接口
     */
    public function doPageUpdate()
    {
        global $_GPC, $_W;
        $uniacid  = $this->_uniacid;
        $openid  = $_W['openid'];
        $uid  = $_W['member']['uid'];
        /*==============*/
        $allow = array('sec','kbwdl_house','kbwdl_broker','kbwdl_shop');
        $enews = $_GPC['enews'];
        $tablename = $_GPC['tablename'];
        $value = $_GPC['value'];
        $id = $_GPC['id'];
        /*房源下架上架*/
        if($enews =='down' && $tablename==1){             
            pdo_update($allow[$tablename], array('isonline'=> ($value==1 ? '0' : '1') ) , array('id' => $id,'uniacid'=>$uniacid));
                        /*统计数量*/
            $info = pdo_fetch("select broker_id,broker_name from ".tablename("kbwdl_house")." where id='$id' and uniacid='$uniacid'");
            $this->count_broker_send_num($info['broker_id'],$info['broker_name']);
            pdo_insert("kbwdl_actlog", array(
                   'actname'=>'isonline','addtime'=> date('Y-m-d H:i:s', TIMESTAMP),
                   'num'=>1,'ecuid'=>$uid,'acttype'=>4,'infoid'=>$id,'uniacid'=>$uniacid,
                   'note'=>'房源上下架操作_'
               ));
            $this->result(0, "操作成功房源下架上架".$allow[$tablename] );
        }
        /* 设置二手房源属性 */
        if ($enews == 'setattr' && $tablename == 1) {
            $field = $_GPC['field'];
            /*获取天数*/
            $days = 1;
            if(isset($_GPC['topday'])&& !empty($_GPC['topday'])){
                $days = intval($_GPC['topday']);
            }
            pdo_update($allow[$tablename], array($field => $value), array('id' => $id, 'uniacid' => $uniacid));
            pdo_insert("kbwdl_actlog", array(
                'actname' => $field, 'addtime' => date('Y-m-d H:i:s', TIMESTAMP), 'isadd' => $value, /*1 表示设置置顶*/
                'num' => $days, 'ecuid' => $uid, 'acttype' => 4, 'infoid' => $id, 'uniacid' => $uniacid,
                'note' => '设置房源推荐位'
            ));
            /* 扣除积分 */
            if ($_GPC['ispay'] == 1 && $value == 1) { /* 可以扣积分 置顶操作 */
                $prive = $this->_user_prive();
                 /*创建充值记录*/
                load()->model('mc');
                /* 代金券和折扣券的兑换记录, */
                $credit = $prive['credit']['istop'] ;
                $credit = $credit * $days;
                /**/
                mc_credit_update($uid, 'credit2', -$credit, array($uid, '置顶房源使用余额：' . $credit));
                pdo_insert("kbwdl_actlog", array(
                    'actname' => 'downcredit2',
                    'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
                    'money' => $credit, 'ecuid' => $uid, 'acttype' => 3, 'isadd' => 0,
                    'infoid' => $id, 'uniacid' => $uniacid,
                    'note' => '置顶房源使用余额'
                ));
            }
            $this->result(0, "设置房源属性成功".$allow[$tablename] );  
        }
        /*刷新房源*/
        if($enews =='refresh' && $tablename==1){
            /*判断权限*/
             $prive = $this->_user_prive();
             $limit = $prive['refresh_num'];
             $sql = "select SUM(num) from ".tablename("kbwdl_actlog").
                    " where infoid='$id' and actname='refresh' and uniacid='$uniacid'  and (left(`addtime`,10)=left(NOW(),10)) ";
            $ret = pdo_fetchcolumn($sql);

            $info['end_total'] = max(($limit - $ret - 1), 0);
            $info['refresh_time'] = date('Y-m-d H:i:s', TIMESTAMP);
            /* 超过数量不可以刷新 */
            $canrefresh = ( $limit > $ret);
            /* 扣除积分 */
            if ($_GPC['ispay'] == 1) { /* 可以扣积分刷新操作 */
                $prive = $this->_user_prive();
                /* 创建充值记录 */
                load()->model('mc');
                /* 代金券和折扣券的兑换记录, */
                $credit = $prive['credit']['refresh'];
                mc_credit_update($uid, 'credit2', -$credit, array($uid, '刷新房源使用余额：' . $credit));
                pdo_insert("kbwdl_actlog", array(
                    'actname' => 'downcredit2',
                    'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
                    'money' => $credit, 'ecuid' => $uid, 'acttype' => 3, 'isadd' => 0,
                    'infoid' => $id, 'uniacid' => $uniacid,
                    'note' => '刷新房源使用余额'
                ));
                /* 付费模式可以刷新 */
                $canrefresh = true;
                $info['end_total'] = 0;
            }
            /* 不能刷新 */
            if (!$canrefresh) {
                $info['refresh_total'] = $ret;
                $info['end_total'] = 0;                            
                
             }else{  
               $info['refresh_total'] = $ret+1;
              
                pdo_insert("kbwdl_actlog", array(
                    'actname'=>'refresh','addtime'=>$info['refresh_time'],
                    'num'=>1,'ecuid'=>$uid,'acttype'=>4,'infoid'=>$id,'uniacid'=>$uniacid,
                    'note'=>'刷新房源'
                ));
                pdo_update('kbwdl_house', array('refresh_time'=> TIMESTAMP), array('id'=> $id, 'uniacid'=> $uniacid));  
             }
             $this->result(0, "刷新次数达到上限$sql"  , $info );
        }
        /*删除一条房源*/
        if($enews =='delete' && $tablename==1){             
            pdo_delete($allow[$tablename], array('id' => $id,'uniacid'=>$uniacid));
                        /*统计数量*/
            $info = pdo_fetch("select broker_id,broker_name from ".tablename("kbwdl_house")." where id='$id' and uniacid='$uniacid'");
            $this->count_broker_send_num($info['broker_id'],$info['broker_name']);
            $this->result(0, "删除房源成功".$allow[$tablename] );
        }
        /*获取一条房源*/
        if($enews=='fetch' && $id){
            $info = pdo_fetch("select * from ".tablename($allow[$tablename])." where id='$id' and uniacid='$uniacid'");
            $info['attachs'] = unserialize($info['thumb_url']);
            if($info['attachs']){
                foreach($info['attachs'] as $key=>$val){
                    $tmp[$key] = tomedia($val);
                }
                $info['attachs_url'] = $tmp;
            }
            if ($info['zhutype'] == '3') {
                /* 生意转让 */
                $tmp = explode(',', $info['disposition']);
                $info['hangye'] = $tmp[0];
                $info['jingyin'] = $tmp[1];
            }
            /*求租求购*/
            if ($info['zhutype'] == '4') {
                /* 生意转让 */
                $tmp = explode(',', $info['disposition']);
                $info['sufix'] = $tmp[0];
                $info['price'] = $tmp[1];
            }
            /*处理 写字楼、商铺 租金 元/㎡/月
            if($info['danyuan'] && $info['menpai']){
                if($info['zhutype']>0){
                    $info['loyer'] = $info['danyuan'];
                    $info['prix_unitaire'] = $info['menpai'];
                }
            }*/
            /*视频地址*/
            if($info['video']){
                $info['video_src'] = tomedia($info['video']);
            }
            if($this->module['config']['isduocity']==1){               
                $info['quan'] = $info['area'];
                $info['area'] = $info['cityname'];
            }
            $this->result(0, "查询一条房源".$allow[$tablename], $info );
        }
        /*管理二手房 推广的时候*/
        if($enews=='managesechouse' && $id){
            /*判断权限*/
            $prive = $this->_user_prive();
            $refresh_num = $prive['refresh_num'] ;
            $istop_num = $prive['istop_num'];
             /**/
            $info = pdo_fetch("select * from ".tablename($allow[$tablename])." where id='$id' and uniacid='$uniacid'");
            $ref = $info['refresh_time'] ?  $info['refresh_time']: $info['update_time'];
            $info['refresh_time'] = date('Y-m-d H:i:s', $ref);
            $sql = "select SUM(num) from ".tablename("kbwdl_actlog").
                    " where infoid='$id' and actname='refresh' and uniacid='$uniacid'  and (left(`addtime`,10)=left(NOW(),10)) ";
            $ret = pdo_fetchcolumn($sql);
            if(!empty($ret)){
                $info['refresh_total'] = $ret;
                $info['end_total'] = max(0,$refresh_num - $ret);
            }else{
                $info['refresh_total'] = 0;
                $info['end_total'] = $refresh_num;
            }
            /*置顶房源数*/
            $broker_id = pdo_fetchcolumn("select id from ".tablename("kbwdl_broker")." where uniacid='$uniacid' and openid='$openid'");
            if($broker_id){
               $sql =  "select count(*) from ".tablename("kbwdl_house")." where istop=1 and uniacid='$uniacid' and  broker_id='$broker_id'";
            }else{
                $sql = "select count(*) from ".tablename("kbwdl_house")." where istop=1 and uniacid='$uniacid' and  broker_name='$openid'";
            }
            $hasnum = pdo_fetchcolumn($sql);
            $info['istop_total'] = $hasnum;
            $info['istop_end_total'] = max(0,$istop_num - $hasnum) ;
            /*发布权限*/
            $info['prive'] = $prive;
            $info['member'] = $_W['member'];
            /**/
            $this->result(0, "查询一条房源 $openid " . $sql, $info);
        }
        /* 升级经济人vip */
        if ($enews == 'buygroup') {
            /* 扣除余额 */
            if (isset($_GPC['needcredit'])) {
                
            }
            $this->result(0, "升级成功"  , $this->_user_prive());
        }
        /* 积分兑换成余额 */
        if ($enews == 'transjifen') {
            $trans = intval($_GPC['credit']);
            $fee = intval($_GPC['money']);
            if ($fee > intval($_W['member']['credit1'])) {
                return $this->result(1, '账号积分不足');
            }
            load()->model('mc');
            /* 记录积分兑换操作 */
            pdo_insert("kbwdl_actlog", array(
                'actname' => 'transjifen',
                'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
                'money' => $fee, 'ecuid' => $uid, 'acttype' => 1, 'isadd' => 0,
                'infoid' => 0, 'uniacid' => $uniacid,
                'note' => '积分兑换成'
            ));
            /* 记录消费积分日志 */
            pdo_insert("kbwdl_actlog", array(
                'actname' => 'downcredit1',
                'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
                'money' => $fee, 'ecuid' => $uid, 'acttype' => 8, 'isadd' => 0,
                'infoid' => 0, 'uniacid' => $uniacid,
                'note' => '积分兑换成余额消费积分'
            ));
            /* 记录增加余额日志 */
            pdo_insert("kbwdl_actlog", array(
                'actname' => 'addcredit2',
                'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
                'money' => $trans, 'ecuid' => $uid, 'acttype' => 2, 'isadd' => 1,
                'infoid' => 0, 'uniacid' => $uniacid,
                'note' => '积分兑换成余额'
            ));
            mc_credit_update($uid, 'credit1', -$fee, array($uid, $fee . '积分兑换余额：' . $trans));
            mc_credit_update($uid, 'credit2', +$trans, array($uid, $fee . '积分兑换余额：' . $trans));

            return $this->result(0, '', array($fee, $trans));
        }
    }
 
    /**
     * 发起支付功能
     */
    public function doPagePay()
    {
        global $_GPC, $_W;	
        $uniacid  = $this->_uniacid;
        $openid  = $_W['openid'];
        $uid  = $_W['member']['uid'];
        $fee = trim($_GPC['money']);
        $actname = trim($_GPC['actname']);
        /* 生成下单记录 */
        pdo_insert("kbwdl_actlog", array(
            'actname' => $actname,
            'addtime' => date('Y-m-d H:i:s', TIMESTAMP),
            'money' => $fee, 'ecuid' => $uid, 'acttype' => 9,
            'infoid' => 0, 'uniacid' => $uniacid,
            'note' => '发起微信支付订单'
        ));
        $orderid = pdo_insertid();
        /* 构造支付参数 */
        $order = array(
            'tid' => $orderid,
            'user' => $openid,
            'fee' => floatval($fee),
            'title' => '微信支付',
        );
        /* 生成支付参数，返回给小程序端 */
        $pay_params = $this->pay($order);

        if (is_error($pay_params)) {
            return $this->result(1, '支付失败，请重试');
        }
        return $this->result(0, '', $pay_params);
    }
    /**
     * 支付处理
     */
    public function payResult($log) {
        global $_GPC, $_W;
        $uniacid = $log['uniacid'];
        $openid = $_W['openid'];
        $uid = $log['tag']['uid'];
        /* load()->func('logging');          
          logging_run($log); */

        if ($log['tid']) {
            $sn = $log['tid'];
            $order = pdo_fetch("select * from " . tablename("kbwdl_actlog") . " where uniacid='$uniacid' and ecuid='$uid' and id='$sn'");

            if ($log['from'] == 'notify') {
                if ($order['actname'] == 'makeorder') {
                    /* 余额充值处理 */
                    $this->_pay_notice_credit2($log, $order);
                } elseif ($order['actname'] == 'buygroup_pay') {
                    $this->_pay_notice_buygroup($log, $order);
                }
                /* 完成支付订单 */
                pdo_update('kbwdl_actlog', array('mark' => 'success'), array('id' => $order['id']));
                return $this->result(0, '支付成功', $log);
            }
        }

        return $this->result(0, '支付失败', $log);
    }
 
    public function _calcute_bill($money){
        $bd = $this->module['config']['credit'] ;
        $credit = 0;
        $money = intval($money);
        if($bd['bill_method']==2){
          if ($money >= intval($bd['jieti3'])  ) {
              $credit = $bd['jieti3_bill'];
          } else if ($money >=  intval($bd['jieti2']) ){
              $credit =$bd['jieti2_bill'];
          } else if ($money >=intval($bd['jieti1']) ) {
              $credit = $bd['jieti1_bill'];
            }else{
              $credit = $money;
            }
        }else{
          $bill = intval($bd['bill']);
          if(!$bill){
              $bill = 10;
          }
          $credit = $money * $bd['bill'];
        }
        return $credit;
    }
    
    
    /* 2020年8月发送给房源经纪人消息 信息
     * $gpc = array(
     * title, nickname,mobile
     * brokerid = 要通知的经纪人
     */
    public function _notice_parent_broker( $gpc, $fnt='客户预约'){
       global $_W, $_GPC;
       $uniacid = $this->_uniacid;
       $openid = $_W['openid'];  
       $touser = ""; /*发送人不填写默认发送给管理员。*/
       if(isset($gpc['brokerid']) && !empty($gpc['brokerid'])){
           $parent_bid = intval($gpc['brokerid']);
           $title = $gpc['title'];
           $pbroker = pdo_fetch("select * from ".tablename("kbwdl_broker"). " where uniacid='$uniacid' and id='$parent_bid'");
           pdo_insert("kbwdl_share_user", array(
               'uid'=> 0, 
               'openid'=>$openid,
               'parent_openid'=> $pbroker['openid'],
               'parent_uid'=> $pbroker['ecuid'],
               'name'=>  $gpc['nickname'],
               'mobile'=> $gpc['mobile'],
               'addtime'=> TIMESTAMP,
               'uniacid'=> $uniacid,
               'identify'=>$pbroker['gzhopenid']
           ));
           $touser = $pbroker['gzhopenid'];
            
       } 
     return    $this->save_send_notice_account('feed_notice',
                        $fnt,
                        $gpc['title'],
                        "客户：".$gpc['nickname'],
                        "手机号：".$gpc['mobile'],
                        $touser);
            
    }
    /*获取模块参数设置内容*/
    public function _getSetting(){
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        $sql = 'SELECT `settings` FROM ' . tablename('uni_account_modules') . ' WHERE `uniacid` = :uniacid AND `module` = :module';
        $settings = pdo_fetchcolumn($sql, array(':uniacid' => $uniacid, ':module' => 'kbwdl_shequzufang'));
        $ret=   iunserializer($settings);
        /*初始化一下配置参数*/
        if(!isset($ret['indexshare'])){
            $ret['indexshare'] = 0;
        }
        if(!isset($ret['isduocity'])){
            $ret['isduocity'] = 0;
        }
        if(!isset($ret['chognzhi'])){
            $ret['chognzhi'] = 0;
        }
        return $ret;
    }
     
    public function _house_list_field()
    {
        return  'id, newshouse_id as hid,title,face,average_price,min_price,max_price,tprice,unit1,unit2,sale,logo,prowedt,nature,type,region,paymethod,mark,poster, fcatid,fid, price_info,uniacid,selltelephone,address,main';
    }
    /*格式化楼盘 的地图数据*/
    public function _format_map_point($lon, $lat)
    {
        $bd_lon  = $lon;//$val['map_x'];
        $bd_lat  = $lat;//$val['map_y'];
        $X_PI = M_PI * 3000.0 / 180.0;  
        $x = $bd_lon - 0.0065;  
        $y = $bd_lat - 0.006;  
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $X_PI);  
        $theta = atan2($y, $x) - 0.000003 * cos($x * $X_PI);  
        $val[0] = $z * cos($theta);  
        $val[1] = $z * sin($theta); 
           
      return $val;     
    }
    /*格式化楼盘列表数据 $ischarges 分销, $groupid 用户类型*/
    public function _format_newhouse_item($val, $ischarges=0, $groupid=0)
    {
        if(empty($val)){
            return array();
        }
        /*处理只显示三个的列表*/
        $prowedt = explode(',',$val['prowedt']);
        $val['prowedt_all'] = $prowedt;
        $val['prowedt'] = $prowedt;
        if(count($prowedt)>3){
             $val['prowedt']= array($prowedt[0],$prowedt[1],$prowedt[3]);
        } 
         /*项目类型*/ 
        $nature = array('住宅'=>'1','别墅'=>'2','商住'=>'3','商铺'=>'4','低商'=>'5');
        $val['nature'] = explode(',', $val['nature']);
        $val['nature_key'] = $nature[$val['nature'][0]];
        /*封面图*/
        $val['logo'] = tomedia($val['logo']);
        $val['face'] = tomedia($val['face']);
        $val['video'] = tomedia($val['video']);
        if($val['sale']){
            $val['sale_tag'] = $this->other['onsale'][$val['sale']];             
        }else{
            $val['sale_tag'] = '待定';
        }
        if($val['builtuparea']){
            $val['builtuparea'] = $val['builtuparea'] *100 /100;
        }
        /*开盘时间*/
        $val['startselldate'] = 
        $val['startselldate'] ?  $val['startselldate'] : '暂无开盘信息';
        /*价格信息*/
        if($val['tprice']){
            $val['tprice'] = $this->other['pricetype'][$val['tprice']];
        }else{
            $val['tprice'] = '普通住宅';
        }

        if ($val['unit2'] == '平米')
            $val['unit2'] = '㎡';
        if ($val['average_price']) {
            $tag = '均价';
            $price = $val['average_price'] . ' ' . $val['unit1'] . '/' . $val['unit2'];
        } elseif ($val['min_price']) {
            $tag = '起价';
            $price = $val['min_price'] . ' ' . $val['unit1'] . '/' . $val['unit2'];
        } elseif ($val['max_price']) {
            $tag = '最高';
            $price = ' ' . $val['max_price'] . ' ' . $val['unit1'] . '/' . $val['unit2'];
        } else {
            $tag = '价格';
            $price = '待定';
        }
        $val['price'] = $price;
        $val['price_label'] = $tag;
        /*分销类型*/
        $val['ischarges'] = $ischarges;
        $val['groupid'] = $groupid;
        if($groupid >0 && $ischarges==1){
            $val['price_label'] = '佣';
            $val['price'] = $val['management'];
        }
            
        return $val;
    }
    public function _format_saleinfo($val){            
        
        $val['addtime'] = date('Y年m月d日', strtotime($val['addtime']));
        if($val['tags']){
            $val['tags_label'] = $this->other['saletype'][$val['tags']];
        }else{
            $val['tags'] = 1;
            $val['tags_label'] = '销控信息';
        }
        return $val;
    }    
 
    /**
     * 
     * @param type $mobile
     * @return boolean
     * 验证手机号
     */
    public function _checkIsMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('/^1[2345789]\d{9}$/', $mobile) ? true : false;
    }
     
    
    private function _kb_http_request($url, $data = null)
    {
        if (function_exists('curl_init') && function_exists('curl_exec') ) {
              $curl = curl_init();
              curl_setopt($curl, CURLOPT_URL, $url);
              curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
              curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

              if (!empty($data)) {
                  curl_setopt($curl, CURLOPT_POST, TRUE);
                  curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
              }
              curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
              $output = curl_exec($curl);
              curl_close($curl);            
              return $output;
        }else{
            return '{"errcode":"0"}';
        }
    }
    
    /**
     * 图片上传接口
     */
    public function doPageTransfile(){ 
            global $_GPC, $_W; 
            $uniacid = $this->_uniacid;
            $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');  
            $max_file_size = 20000000; //上传文件大小限制, 单位BYTE  
            $save_folder = 'images/'. $uniacid."/".date('Ym')."/";
            $destination_folder = "../attachment/".$save_folder; //上传文件路径  
            
            if (!is_uploaded_file($_FILES["upfile"]['tmp_name']))  
            //是否存在文件  
            {  
                $this->result(404, '图片不存在' );                   
            }  
            $file = $_FILES["upfile"];  
     
            
            if ($max_file_size < $file["size"])  
            //检查文件大小  
            {  
                $this->result(404, '文件太大' );                 
            } 
             

            if (!file_exists($destination_folder)) {  
                mkdir($destination_folder);  
            }  
            $filename = $file["tmp_name"];  
            $pinfo = pathinfo($file["name"]);  
            $ftype = $pinfo['extension'] ?$pinfo['extension']:'png' ;  
            $destination = $destination_folder . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;  
            
            if (!move_uploaded_file($filename, $destination)) {  
                $this->result(404, '移动文件出错' );                
            }  
            $pinfo = pathinfo($destination);  
            $fname = $pinfo['basename']; 
             /*关闭时不用*/
             $config = \Wdl\helper\webHelper::fetch_place_data('setting','security');
            if( $config['closecheck'] == 0 ){            
               /*鉴别内容*/
                load()->func('communication');     
                /*获取小程序access_token*/
                load()->classs('wxapp.account');           
                $obj = new CURLFile( realpath($destination_folder.$fname) );
                $obj->setMimeType("image/jpeg");
                $obj->setPostFilename('media');
                $vfile['media']   =  $obj;          
                
                $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '".$this->_uniacid ."'" );       
                $accObj= new WxappAccount( $account);        
                $ACCESS_TOKEN = $accObj->getAccessToken( );  
                $WxApi = "https://api.weixin.qq.com/wxa/img_sec_check?access_token={$ACCESS_TOKEN}";
                /*JSON_UNESCAPED_UNICODE 确保json数据不被编码*/            
                $ret = $this->_kb_http_request($WxApi, $vfile );
                $ret = json_decode($ret, true);
                
                if(isset($ret['errcode']) && $ret['errcode']){            
                     $this->result(404, '内容安全监测失败', $ret);            
                } /*鉴别结束*/               
            } 
           
            @require_once (IA_ROOT . '/framework/function/file.func.php');  
            @$filename = $fname;  
            @file_remote_upload($save_folder.$fname); 
 
            $this->result(0, 'success',  [
                'thumb' => $save_folder.$fname,
                'url' =>  tomedia($save_folder.$fname)
            ]); 
            
     }  
     /**
      * 上传视频接口
      */
     public function doPageTransVideo(){
            global $_GPC, $_W; 
            $uniacid = $this->_uniacid;
            $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');  
            $max_file_size = 20000000; //上传文件大小限制, 单位BYTE  
            $save_folder = 'images/'. $uniacid."/".date('Ym')."/";
            $destination_folder = "../attachment/".$save_folder; //上传文件路径  
            if (!is_uploaded_file($_FILES["upfile"]['tmp_name']))  
            //是否存在文件  
            {  
                echo "图片不存在!";  
                exit;  
            }  
            $file = $_FILES["upfile"]; 
     

            if (!file_exists($destination_folder)) {  
                mkdir($destination_folder);  
            }  
            $filename = $file["tmp_name"];  
            $pinfo = pathinfo($file["name"]);  
            $ftype = $pinfo['extension'];  
            $destination = $destination_folder . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;  
           
            if (!move_uploaded_file($filename, $destination)) {  
                echo "移动文件出错";  
                exit;  
            }  
            $pinfo = pathinfo($destination);  
            $fname = $pinfo['basename'];  
             
            @require_once (IA_ROOT . '/framework/function/file.func.php');  
            @$filename = $fname;  
            @file_remote_upload($save_folder.$fname); 
            echo $save_folder.$fname.'#'.  tomedia($save_folder.$fname); 
            exit;
     }
     
    /**
     * 通过消息id 发送消息
     */
    public function doPageSendNotice(){
        global $_GPC, $_W;
        $uniacid = $this->_uniacid;
        $openid = $_W['openid'];
        $notice_id = intval( $_GPC['notice_id']);
        if(!$notice_id){
            return false;
        }
        $ret = pdo_fetch("select * from ".tablename("kbwdl_formids")." where id='$notice_id'");
             require  IA_ROOT. "/addons/kbwdl_shequzufang/vender/helper.php";
         $content = iunserializer($ret['formids']);
         $helper = new wdlHelper();
         $gzhinfo = pdo_fetch("select * from ".tablename("kbwdl_config"). " where placeid=41 and uniacid='$uniacid' and module='kbwdl_shequzufang'");
         load()->func('logging');
         //logging_run($gzhinfo);
         if(!empty($gzhinfo['conf_value'])){
             $gzh = iunserializer($gzhinfo['conf_value']);
         }else{
             return false;
         }
         if(empty($gzh['appid']) || empty($gzh['appsecret'])){
             return false;
         }
         $ACCESS_TOKEN  = $helper->getAccessToken($gzh['appid'], $gzh['appsecret']);
         if(!$ACCESS_TOKEN){
             return false; /*token 失败*/
         } 
         if(!empty($content['touser'] )){            
             $content['touser'] = $gzh['adminopenid'];
         }
          /*采用客服消息发送*/
         $text =  '{
                    "touser": "'.$content['touser'].'",
                    "msgtype":"text",
                    "text":
                    {
                     "content":"'.$content['data']['first']['value'].'\n------------------------------\n'
                    .$content['data']['keyword1']['value'].'\n------------------------------\n'
                    .$content['data']['keyword2']['value'].'\n------------------------------\n'
                    .$content['data']['remark']['value'].'"
                    }
                }';
        $texturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACCESS_TOKEN; 
            
          /*获取调用系统的get post 方法*/  
        load()->func('communication');
       
        $ret  = ihttp_post($texturl, $text);
        if(isset($ret['content']['errcode']) && $ret['content']['errcode']=='40001'){
             $ret  = ihttp_post($texturl, $text);
        }
        $ret['sendmsg'] = $text;
        //logging_run($ret);
       $this->result(0, "发送通知", $ret);
    }
 
    /**
     * 新版本采用model扩展代码
     * 重新修改__call方法
     */   
    public function __call($name, $arguments) {
        global $_GPC; 
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        //查看model类是否纯在
        $function_name = strtolower(substr($name, 6));
        $className = "Wdl\\model\\". strtolower( $function_name );
        if(class_exists($className)){
          
        // 使用反射类获取类的方法信息
            $reflectionClass = new \ReflectionClass($className);
        
            $reflectionMethod = $reflectionClass->getMethod( $operation );
            // 创建类的实例
            $instance = $reflectionClass->newInstanceArgs( [$this] );
            $result =  $reflectionMethod->invoke($instance, $arguments);
            return  $this->result($result['code'], $result['msg'], $result['data']);
            
        }
        //如果model类不存在，采用微擎默认的inc/wxapp/里面的文件
		parent::__call($name,  $arguments );
	}
}
